<template>
  <div class="min-h-screen flex items-center justify-center bg-gradient-to-br from-blue-50 to-indigo-50">
    <div class="w-full max-w-md p-8">
      <div class="text-center mb-8">
        <h1 class="text-4xl font-bold text-primary mb-2">蒜苔二维码</h1>
        <p class="text-gray-600">活码平台</p>
      </div>

      <a-card class="shadow-lg rounded-lg overflow-hidden">
        <template #title>
          <div class="text-center text-xl font-bold">登录</div>
        </template>

        <a-tabs v-model:activeKey="activeTab" class="login-tabs">
          <a-tab-pane key="password" tab="密码登录">
            <a-form
              :model="passwordForm"
              @finish="handlePasswordSubmit"
              class="space-y-4"
            >
              <a-form-item
                name="username"
                :rules="[{ required: true, message: '请输入用户名' }]"
              >
                <a-input
                  v-model:value="passwordForm.username"
                  placeholder="请输入用户名"
                  size="large"
                  autocomplete="username"
                >
                  <template #prefix>
                    <user-outlined class="text-gray-400" />
                  </template>
                </a-input>
              </a-form-item>

              <a-form-item
                name="password"
                :rules="[{ required: true, message: '请输入密码' }]"
              >
                <a-input-password
                  v-model:value="passwordForm.password"
                  placeholder="请输入密码"
                  size="large"
                  autocomplete="current-password"
                >
                  <template #prefix>
                    <lock-outlined class="text-gray-400" />
                  </template>
                </a-input-password>
              </a-form-item>

              <div class="flex justify-between items-center">
                <a-checkbox v-model:checked="passwordForm.remember">记住密码</a-checkbox>
                <a class="text-primary hover:text-primary-dark">忘记密码？</a>
              </div>

              <a-form-item>
                <a-button
                  type="primary"
                  html-type="submit"
                  block
                  size="large"
                  :loading="loading"
                  class="h-12 text-lg"
                >
                  登录
                </a-button>
              </a-form-item>
            </a-form>
          </a-tab-pane>

          <a-tab-pane key="sms" tab="短信登录">
            <a-form
              :model="smsForm"
              @finish="handleSmsSubmit"
              class="space-y-4"
            >
              <a-form-item
                name="phone"
                :rules="[
                  { required: true, message: '请输入手机号' },
                  { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号' }
                ]"
              >
                <a-input
                  v-model:value="smsForm.phone"
                  placeholder="请输入手机号"
                  size="large"
                  autocomplete="tel"
                >
                  <template #prefix>
                    <mobile-outlined class="text-gray-400" />
                  </template>
                </a-input>
              </a-form-item>

              <a-form-item
                name="code"
                :rules="[{ required: true, message: '请输入验证码' }]"
              >
                <a-input
                  v-model:value="smsForm.code"
                  placeholder="请输入验证码"
                  size="large"
                  autocomplete="one-time-code"
                >
                  <template #prefix>
                    <safety-outlined class="text-gray-400" />
                  </template>
                  <template #suffix>
                    <a-button
                      type="link"
                      :disabled="countdown > 0"
                      @click="handleSendCode"
                    >
                      {{ countdown > 0 ? `${countdown}秒后重试` : '获取验证码' }}
                    </a-button>
                  </template>
                </a-input>
              </a-form-item>

              <!-- 占位空间，保持与密码登录相同高度 -->
              <div class="mb-4 h-6"></div>

              <a-form-item>
                <a-button
                  type="primary"
                  html-type="submit"
                  block
                  size="large"
                  :loading="loading"
                  class="h-12 text-lg"
                >
                  登录
                </a-button>
              </a-form-item>
            </a-form>
          </a-tab-pane>

          <a-tab-pane key="email" tab="邮箱登录">
            <a-form
              :model="emailForm"
              @finish="handleEmailSubmit"
              class="space-y-4"
            >
              <a-form-item
                name="email"
                :rules="[
                  { required: true, message: '请输入邮箱' },
                  { type: 'email', message: '请输入正确的邮箱格式' }
                ]"
              >
                <a-input
                  v-model:value="emailForm.email"
                  placeholder="请输入邮箱"
                  size="large"
                  autocomplete="email"
                >
                  <template #prefix>
                    <mail-outlined class="text-gray-400" />
                  </template>
                </a-input>
              </a-form-item>

              <a-form-item
                name="code"
                :rules="[{ required: true, message: '请输入验证码' }]"
              >
                <a-input
                  v-model:value="emailForm.code"
                  placeholder="请输入验证码"
                  size="large"
                  autocomplete="one-time-code"
                >
                  <template #prefix>
                    <safety-outlined class="text-gray-400" />
                  </template>
                  <template #suffix>
                    <a-button
                      type="link"
                      :disabled="emailCountdown > 0"
                      @click="handleSendEmailCode"
                    >
                      {{ emailCountdown > 0 ? `${emailCountdown}秒后重试` : '获取验证码' }}
                    </a-button>
                  </template>
                </a-input>
              </a-form-item>

              <!-- 占位空间，保持与密码登录相同高度 -->
              <div class="mb-4 h-6"></div>

              <a-form-item>
                <a-button
                  type="primary"
                  html-type="submit"
                  block
                  size="large"
                  :loading="loading"
                  class="h-12 text-lg"
                >
                  登录
                </a-button>
              </a-form-item>
            </a-form>
          </a-tab-pane>

          <a-tab-pane key="wechat" tab="微信登录">
            <div class="wechat-login-container">
              <WeChatLogin @success="handleWeChatLoginSuccess" @error="handleWeChatLoginError" />
            </div>
          </a-tab-pane>
        </a-tabs>

        <div class="text-center">
          <span class="text-gray-500">还没有账号？</span>
          <router-link to="/auth/register" class="text-primary hover:text-primary-dark ml-1">
            立即注册
          </router-link>
        </div>
      </a-card>

      <div class="text-center mt-8 text-gray-500 text-sm">
        Copyright © 2025 AnyPay. All rights reserved.
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref } from 'vue'
import { useRouter } from 'vue-router'
import { message } from 'ant-design-vue'
import { UserOutlined, LockOutlined, MobileOutlined, SafetyOutlined, MailOutlined } from '@ant-design/icons-vue'
import { anyPost } from '@/network'
import { useUserStore } from '@/stores/user'
import WeChatLogin from '@/components/WeChatLogin.vue'

const router = useRouter()
const userStore = useUserStore()
const loading = ref(false)
const activeTab = ref('password')
const countdown = ref(0)
const emailCountdown = ref(0)

const passwordForm = reactive({
  username: '',
  password: '',
  remember: false,
})

const smsForm = reactive({
  phone: '',
  code: '',
})

const emailForm = reactive({
  email: '',
  code: '',
})

const handlePasswordSubmit = async () => {
  loading.value = true
  try {
    const response = await anyPost('/api/auth/login', {
      username: passwordForm.username,
      password: passwordForm.password,
      authType: 'password'
    })

    if (response.code === 200 || response.success) {
      // 存储token和用户信息
      const { token, userInfo, permissions } = response.data
      userStore.setToken(token)
      userStore.setUserInfo(userInfo)

      // 存储权限信息到localStorage（可选）
      if (permissions) {
        localStorage.setItem('permissions', JSON.stringify(permissions))
      }

      message.success('登录成功')
      
      // 检查是否有保存的二维码生成状态，如果有则跳转回二维码页面
      const savedState = sessionStorage.getItem('qrcode_generation_state')
      if (savedState) {
        router.push({
          path: '/qrcode',
          replace: true
        })
      } else {
        router.push({
          path: '/admin/dashboard',
          replace: true
        })
      }
    } else {
      message.error(response.message || '登录失败')
    }
  } catch (error: any) {
    message.error(error.message || '登录失败')
  } finally {
    loading.value = false
  }
}

const handleSendCode = async () => {
  try {
    if (!smsForm.phone || !/^1[3-9]\d{9}$/.test(smsForm.phone)) {
      message.error('请输入正确的手机号')
      return
    }

    const response = await anyPost('/api/auth/sms/send', {
      phone: smsForm.phone
    })

    if (response.code === 200 || response.success) {
      message.success('验证码发送成功')
      countdown.value = 60
      const timer = setInterval(() => {
        countdown.value--
        if (countdown.value <= 0) {
          clearInterval(timer)
        }
      }, 1000)
    } else {
      message.error(response.message || '验证码发送失败')
    }
  } catch (error: any) {
    message.error(error.message || '验证码发送失败')
  }
}

const handleSmsSubmit = async () => {
  loading.value = true
  try {
    const response = await anyPost('/api/auth/sms/verify', {
      phone: smsForm.phone,
      code: smsForm.code
    })

    if (response.code === 200 || response.success) {
      // 存储token和用户信息
      const { token, userInfo, permissions } = response.data
      userStore.setToken(token)
      userStore.setUserInfo(userInfo)

      // 存储权限信息到localStorage（可选）
      if (permissions) {
        localStorage.setItem('permissions', JSON.stringify(permissions))
      }

      message.success('登录成功')
      
      // 检查是否有保存的二维码生成状态，如果有则跳转回二维码页面
      const savedState = sessionStorage.getItem('qrcode_generation_state')
      if (savedState) {
        router.push({
          path: '/qrcode',
          replace: true
        })
      } else {
        router.push({
          path: '/admin/dashboard',
          replace: true
        })
      }
    } else {
      message.error(response.message || '登录失败')
    }
  } catch (error: any) {
    message.error(error.message || '登录失败')
  } finally {
    loading.value = false
  }
}

const handleSendEmailCode = async () => {
  try {
    if (!emailForm.email || !/^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$/.test(emailForm.email)) {
      message.error('请输入正确的邮箱')
      return
    }

    const response = await anyPost('/api/auth/email/send', {
      email: emailForm.email
    })

    if (response.code === 200 || response.success) {
      message.success('验证码发送成功')
      emailCountdown.value = 60
      const timer = setInterval(() => {
        emailCountdown.value--
        if (emailCountdown.value <= 0) {
          clearInterval(timer)
        }
      }, 1000)
    } else {
      message.error(response.message || '验证码发送失败')
    }
  } catch (error: any) {
    message.error(error.message || '验证码发送失败')
  }
}

const handleEmailSubmit = async () => {
  loading.value = true
  try {
    const response = await anyPost('/api/auth/email/verify', {
      email: emailForm.email,
      code: emailForm.code
    })

    if (response.code === 200 || response.success) {
      // 存储token和用户信息
      const { token, userInfo, permissions } = response.data
      userStore.setToken(token)
      userStore.setUserInfo(userInfo)

      // 存储权限信息到localStorage（可选）
      if (permissions) {
        localStorage.setItem('permissions', JSON.stringify(permissions))
      }

      message.success('登录成功')
      router.push({
        path: '/admin/dashboard',
        replace: true
      })
    } else {
      message.error(response.message || '登录失败')
    }
  } catch (error: any) {
    message.error(error.message || '登录失败')
  } finally {
    loading.value = false
  }
}

const handleWeChatLoginSuccess = (data: any) => {
  // 处理微信登录成功
  const { token, userInfo, permissions } = data
  userStore.setToken(token)
  userStore.setUserInfo(userInfo)

  // 存储权限信息到localStorage（可选）
  if (permissions) {
    localStorage.setItem('permissions', JSON.stringify(permissions))
  }

  message.success('微信登录成功')
  
  // 检查是否有保存的二维码生成状态，如果有则跳转回二维码页面
  const savedState = sessionStorage.getItem('qrcode_generation_state')
  if (savedState) {
    router.push({
      path: '/qrcode',
      replace: true
    })
  } else {
    router.push({
      path: '/admin/dashboard',
      replace: true
    })
  }
}

const handleWeChatLoginError = (error: any) => {
  // 处理微信登录失败
  message.error(error.message || '微信登录失败')
}
</script>

<style scoped>
.ant-card {
  border-radius: 12px;
  border: none;
}

.ant-input-affix-wrapper {
  border-radius: 8px;
  height: 48px;
}

.ant-input-affix-wrapper:hover,
.ant-input-affix-wrapper-focused {
  border-color: var(--primary-color);
  box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.1);
}

.ant-btn {
  border-radius: 8px;
  font-weight: 500;
}

.ant-checkbox-wrapper {
  color: #666;
}

.text-primary {
  color: var(--primary-color);
}

.text-primary-dark {
  color: #096dd9;
}

/* 解决Tab切换时的抖动问题 */
.login-tabs .ant-tabs-content-holder {
  min-height: 280px; /* 设置固定最小高度 */
}

.login-tabs .ant-tabs-tabpane {
  min-height: 280px;
}

.wechat-login-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  min-height: 280px;
  padding: 40px 0;
}
</style>